$(function(){
	//用来存储节点的顺序
    var connections = [];
    //拖动节点开始时的事件
    var dragger = function () {
        this.ox = this.attr("x");
        this.oy = this.attr("y");
        this.animate({ "fill-opacity": .2 }, 500);
    };
    //拖动事件
    var move = function (dx, dy) {
        var att = { x: this.ox + dx, y: this.oy + dy };
        this.attr(att);
        $("#node" + this.id).offset({ top: this.oy + dy + 10, left: this.ox + dx + 10 });//id is begin from one
        for (var i = connections.length; i--; ) {
            r.drawArr(connections[i]);
        }
    };
  //拖动结束后的事件
    var up = function () {
        this.animate({ "fill-opacity": 0 }, 500);
    };
    var FlowNode = function(){
    	id : id,
    	tag : tag,
    	nextNode : nextNode,
    	position : position
    };
    var drawNode = function(){
    	var r = Raphael("holder", $(window).width(), $(window).height());
    }
    var drawFlow = function(fNodesJson){
	    var jsonLen = fNodesJson.length;
	    //创建绘图对象
	    var r = Raphael("holder", $(window).width(), $(window).height());
	    //绘制节点 、、、、、、、、、、、、动态绘制节点图形 w h 宽 高
	    var shapes = [];
	    var view = $('#view');
	    $.each(fNodesJson,function(ids,item){
	    	nextNodes = item.nextNode;
	    	nextNodeLen = nextNodes.length;
	    	//alert(nextNodeLen);
	    	if(ids%2 == 0){
	    		shapes.push(r.rect(190+ids*80,100,60,40,4));
	    		view.append('<div id='+item.id+">"+item.tag+"</div>") //这里的内容要可变
	        	//view.attr(); //这里给他加入css可以设置他的显示图片，来标记他是什么结点。
	        	$("#"+item.id).offset({
	        		top : 100 + 10,
	        		left: 190 + ids*80 + 10
	        	});
	    	}else{
	    		shapes.push(r.rect(190+ids*80,180,60,40,4));
	    		view.append('<div id='+item.id+">"+item.tag+"</div>") //这里的内容要可变
	        	//view.attr(); //这里给他加入css可以设置他的显示图片，来标记他是什么结点。
	        	$("#"+item.id).offset({
	        		top : 180 + 10,
	        		left: 190 + ids*80 + 10
	        	});
	    	}
	    });
	   
	    //定位节点上的文字，、、、、、、、、、动态插入div top  left 跟据上面的 w h来确定
	    //为节点添加样式和事件，并且绘制节点之间的箭头
	    for (var i = 0, ii = shapes.length; i < ii; i++) {
	        var color = Raphael.getColor();
	        shapes[i].attr({ fill: color, stroke: color, "fill-opacity": 0, "stroke-width": 2, cursor: "move" });
	        shapes[i].id = i + 1;
	        shapes[i].drag(move, dragger, up);
	        shapes[i].dblclick(function () { alert(this.id) })
	    }
	    //存储节点间的顺序  HERE 通过循环插入节点
	    for (var i = 0;i<shapes.length-1;i++){
	    	connections.push(r.drawArr({
	    		obj1: shapes[i],
	    		obj2: shapes[i+1]
	    	}));
	    }
    }
    var fNodesJson = [{
    	id:1,
    	tag:"start",
    	nextNode:[2]
    },
     {
    	id:2,
    	tag:"node1",
    	nextNode:[3]
    },
    {
    	id:3,
    	tag:"node2",
    	nextNode:[4]
    },
    {
    	id:4,
    	tag:"end",
    	nextNode:"none"
    }];
   
	drawFlow(fNodesJson);
});

//随着节点位置的改变动态改变箭头
Raphael.fn.drawArr = function (obj) {
    var point = getStartEnd(obj.obj1, obj.obj2);
    var path1 = getArr(point.start.x, point.start.y, point.end.x, point.end.y, 8);
    if (obj.arrPath) {
        obj.arrPath.attr({ path: path1 });
    } else {
        obj.arrPath = this.path(path1);
    }
    return obj;
};

function getStartEnd(obj1, obj2) {
    var bb1 = obj1.getBBox(),
        bb2 = obj2.getBBox();
    var p = [
            { x: bb1.x + bb1.width / 2, y: bb1.y - 1 },
            { x: bb1.x + bb1.width / 2, y: bb1.y + bb1.height + 1 },
            { x: bb1.x - 1, y: bb1.y + bb1.height / 2 },
            { x: bb1.x + bb1.width + 1, y: bb1.y + bb1.height / 2 },
            { x: bb2.x + bb2.width / 2, y: bb2.y - 1 },
            { x: bb2.x + bb2.width / 2, y: bb2.y + bb2.height + 1 },
            { x: bb2.x - 1, y: bb2.y + bb2.height / 2 },
            { x: bb2.x + bb2.width + 1, y: bb2.y + bb2.height / 2 }
        ];
    var d = {}, dis = [];
    for (var i = 0; i < 4; i++) {
        for (var j = 4; j < 8; j++) {
            var dx = Math.abs(p[i].x - p[j].x),
                dy = Math.abs(p[i].y - p[j].y);
            if (
                 (i == j - 4) ||
                 (((i != 3 && j != 6) || p[i].x < p[j].x) &&
                 ((i != 2 && j != 7) || p[i].x > p[j].x) &&
                 ((i != 0 && j != 5) || p[i].y > p[j].y) &&
                 ((i != 1 && j != 4) || p[i].y < p[j].y))
               ) {
                dis.push(dx + dy);
                d[dis[dis.length - 1]] = [i, j];
            }
        }
    }
    if (dis.length == 0) {
        var res = [0, 4];
    } else {
        res = d[Math.min.apply(Math, dis)];
    }
    var result = {};
    result.start = {};
    result.end = {};
    result.start.x = p[res[0]].x;
    result.start.y = p[res[0]].y;
    result.end.x = p[res[1]].x;
    result.end.y = p[res[1]].y;
    return result;
}
//获取组成箭头的三条线段的路径
function getArr(x1, y1, x2, y2, size) {
    var angle = Raphael.angle(x1, y1, x2, y2);//得到两点之间的角度
    var a45 = Raphael.rad(angle - 45);//角度转换成弧度
    var a45m = Raphael.rad(angle + 45);
    var x2a = x2 + Math.cos(a45) * size;
    var y2a = y2 + Math.sin(a45) * size;
    var x2b = x2 + Math.cos(a45m) * size;
    var y2b = y2 + Math.sin(a45m) * size;
    var result = ["M", x1, y1, "L", x2, y2, "L", x2a, y2a, "M", x2, y2, "L", x2b, y2b];
    return result;
}